#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


//#define Debug -1
#define NUM 1024
#define SIZE 64
#define SEP " "

const char* getUsername()
{
    const char* name = getenv("USER");
    if(name)
        return name;
    return "none";
}
const char* getHostname()
{
     const char* name = getenv("HOSTNAME");
    if(name)
        return name;
    return "none";
}
const char* getCwd()
{
    const char* name = getenv("PWD");
    if(name)
        return name;
    return "none";
}

int getUsercommit(char commit[], int num)
{
    printf("[%s@%s %s]# ", getUsername(), getHostname(), getCwd());
    char* r = fgets(commit, num, stdin);
    if(r == NULL)
        return -1;//获取错误    
    commit[strlen(commit) - 1] = '\0';
    return strlen(commit);
}

void Separate(char in[], char* out[])
{
    int argc = 0;
    out[argc++] = strtok(in, SEP);
    while(out[argc++] = strtok(NULL, SEP));
#ifdef Debug
    for(int i = 0; i < argc; i++)
    {
        printf("argv[%d]:%s\n", i, out[i]);
    } 
#endif
}

void Execute(char* argv[])
{
        pid_t id = fork();
        if(id < 0)
            return ;//创建失败，本次命令失效
        else if(id == 0)//child
        {
            execvp(argv[0], argv);
            exit(1);
        }
        else{
            pid_t rid = waitpid(id, NULL, 0);
        }
}

int main()
{
    while(1)
    {
        char Usercommit[NUM];
        char* argv[SIZE];
        //提示符 && 获取用户指令
        int n = getUsercommit(Usercommit, sizeof(Usercommit));
        if(n <= 0)
            continue;
        //分割指令字符串
        Separate(Usercommit, argv);

        //执行指令
        Execute(argv);
    }
    return  0;
}




